using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace SimpleFramework
{
#if UNITY_EDITOR
    [System.Serializable]
#endif
    public class DictionaryEx<TKey, TValue>
    {
#if UNITY_EDITOR
        [SerializeField]
#endif
        protected List<TKey> m_Keys = new List<TKey>();
        protected Dictionary<TKey, TValue> m_Dict = new Dictionary<TKey, TValue>();

#if UNITY_EDITOR
        [SerializeField]
        protected List<TValue> m_Values = new List<TValue>();
#endif

        public TValue this[TKey key]
        {
            get
            {
                return m_Dict[key];

            }

            set
            {
                m_Dict[key] = value;
            }
        }

        public List<TKey> Keys
        {
            get
            {
                return m_Keys;
            }
        }

        public Dictionary<TKey, TValue> Dict
        {
            get
            {
                return m_Dict;
            }
        }

        public void Add(TKey key, TValue val)
        {
            m_Dict.Add(key, val);
            m_Keys.Add(key);
#if UNITY_EDITOR
            m_Values.Add(val);
#endif
        }

        public void Clear()
        {
            m_Dict.Clear();
            m_Keys.Clear();
#if UNITY_EDITOR
            m_Values.Clear();
#endif
        }

        public bool ContainsKey(TKey key)
        {
            return m_Dict.ContainsKey(key);
        }

        public bool ContainsValue(TValue value)
        {
            return m_Dict.ContainsValue(value);
        }

        public bool Remove(TKey key)
        {
#if UNITY_EDITOR
            int index = m_Keys.IndexOf(key);
            m_Values.RemoveAt(index);
#endif
            m_Keys.Remove(key);
            return m_Dict.Remove(key);
        }
        
        public bool TryGetValue(TKey key, out TValue value)
        {
            return m_Dict.TryGetValue(key, out value);
        }

        public void Remove(System.Func<TValue, bool> check)
        {
            TKey key;
            int i = 0;
            while (i < m_Keys.Count)
            {
                key = m_Keys[i];
                if (check(m_Dict[key]))
                {
                    m_Keys.RemoveAt(i);
                    m_Dict.Remove(key);
#if UNITY_EDITOR
                    m_Values.RemoveAt(i);
#endif
                }
                else
                {
                    ++i;
                }
            }
        }
    }
}